<template>
  <page-meta :root-font-size="rootFontSize() + 'px'"></page-meta>

  <view class="page-container" v-show="delayShow">
    <customHeader isShowProcess :progress="progress" title="听力练习" :border-line="false" />
    <view class="container" :style="{ top: height }">
      <text class="tip">根据听到的题干，选择正确选项</text>
      <image class="ikon" :src="env.prefixUrl + currentQuestion().img"></image>
      <loudspeaker class="loudspeaker" :is-play="isPlayQuestion" @on-click="doPlayQuestion"></loudspeaker>

      <view class="operate-container">
        <view class="optionsContainer">
          <view class="optionContainer" v-for="(item, index) in isShowOptionAnimations" :key="index"
            :class="{ optionAnimation: isShowOptionAnimations[index] }" @click="doSelect(index)">
            <view class="option" :style="{ backgroundColor: buttonBackgroundColor(index) }">
              {{ ["A", "B", "C", "D"][index] }}
            </view>
            <view class="mask" :class="{ maskDisappear: isShowOptionAnimations[index] }"></view>
          </view>
        </view>
        <button class="button"
          :style="{ backgroundColor: selectedOptionIndex >= 0 ? '#C5CE71' : '#E3E3DB', opacity: isSubmitAnswer ? 0 : 1 }"
          @click="doNext">
          提交
        </button>
      </view>

    </view>
  </view>

  <CwCommon />
</template>

<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app";
import { onMounted, ref, computed, nextTick } from "vue";
import { rootFontSize } from "@/utils/util";
import env from "@/config/env";
import API from "@/api";
import loudspeaker from "@/components/loudspeaker.vue";
import customHeader from "@/components/customHeader.vue";
import { AudioManager } from "@/utils/AudioManager";
import type { ILessonResult } from "@/pages/lowPricedCourse/trialCourseHome/courseList/index.vue";
import { useDelayShow } from "@/hooks/useDelayShow";

const { delayShow } = useDelayShow();

export interface IListenTrainingResult extends Omit<ILessonResult, "data"> {
  data: IResult;
}

export interface IResult {
  listen: IQuestion[];
  currentQuestionIndex: number;
}

interface IQuestion {
  listen_id: number;
  img: string;
  us_voice: string;
  uk_voice: string;
  is_select: number;
  option: IOption[];
}

interface IOption {
  option_id: number;
  us_voice: string;
  uk_voice: string;
  answer: number;
  select_this: number;
}

const currentQuestionIndex = ref(0);
const height = ref(getApp().globalData!.pageTop);
const isShowOptionAnimations = ref([false, false, false]);
const questions = ref<IQuestion[] | []>([]);
const isPlayQuestion = ref(false);
const selectedOptionIndex = ref(-1);
const isSubmitAnswer = ref(false);
const isPlayWholeQuestionAnimation = ref(false);

var sectionId: number | null = null;
var isRelearn = false;

onLoad(async (option: any) => {
  sectionId = option.section_id;
  let data = JSON.parse(decodeURIComponent(option.data)) as IListenTrainingResult;
  isRelearn = data.isRelearn;
  questions.value = data.data.listen || [];
  currentQuestionIndex.value = data.data.currentQuestionIndex;
  isPlayWholeQuestionAnimation.value = true;
  playCurrentQuestion(true);
});

const currentQuestion = () => {
  return questions.value![currentQuestionIndex.value] || {};
};

const progress = computed(() => {
  const num = (currentQuestionIndex.value / questions.value!?.length) * 100;
  return num;
});

/** step 第几个音频 */
const playCurrentOptions = (index: number, isPlayNext: boolean = false) => {
  AudioManager.getInstance().play({
    src: env.prefixUrl + currentQuestion().option[index].us_voice,
    onVoiceStart: () => {
      isShowOptionAnimations.value[index] = true;
    },
    onVoiceEnded: () => {
      if (!isPlayNext) {
        return;
      }
      if (index < currentQuestion().option.length - 1) {
        playCurrentOptions(index + 1, isPlayNext);
      } else {
        isPlayWholeQuestionAnimation.value = false;
      }
    },
  });
};

const playCurrentQuestion = (isPlayOption: boolean) => {
  AudioManager.getInstance().play({
    src: env.prefixUrl + currentQuestion().us_voice,
    onVoiceStart: () => {
      isPlayQuestion.value = true;
    },
    onVoiceEnded: () => {
      isPlayQuestion.value = false;
      if (isPlayOption) {
        playCurrentOptions(0, true);
      }
    },
  });
};

const buttonBackgroundColor = (index: number) => {
  let options = currentQuestion().option;
  if (!isSubmitAnswer.value) {
    return selectedOptionIndex.value === index ? "#FEE1AD" : "transparent";
  } else {
    if (options[index].select_this === 1) {
      return options[index].answer === 1 ? "#E9EDBE" : "#FFC6B0";
    } else {
      return options[index].answer === 1 ? "#E9EDBE" : "transparent";
    }
  }
};

const doPlayQuestion = () => {
  if (isPlayWholeQuestionAnimation.value) {
    return;
  }
  playCurrentQuestion(false);
};

const doSelect = (index: number) => {
  if (isPlayWholeQuestionAnimation.value) {
    return;
  }
  selectedOptionIndex.value = index;
  currentQuestion().is_select = 1;
  currentQuestion().option.forEach((option, itemIndex) => {
    option.select_this = index === itemIndex ? 1 : 0;
  });
  playCurrentOptions(index, false);
};

const doNext = async () => {
  if (selectedOptionIndex.value < 0) {
    return;
  }
  if ((await reportQuestionAnswer()) === 0) {
    return;
  }
  isSubmitAnswer.value = true;

  AudioManager.getInstance().play({
    src:
      currentQuestion().option[selectedOptionIndex.value].answer === 1
        ? "https://recite-words.oss-cn-hangzhou.aliyuncs.com/web/Lesson/audio/SKU_Listen_Right.mp3"
        : "https://recite-words.oss-cn-hangzhou.aliyuncs.com/web/Lesson/audio/SKU_Listen_Wrong.mp3",
  });

  setTimeout(async () => {
    if (currentQuestionIndex.value === questions.value!.length - 1) {
      uni.redirectTo({
        url: `/pages/lowPricedCourse/trialCourseHome/transitionPage/index?lastCourseStep=${1}&courseStep=${2}&section_id=${sectionId!}`,
      });
    } else {
      currentQuestionIndex.value++;
      selectedOptionIndex.value = -1;
      isShowOptionAnimations.value = [false, false, false];
      isSubmitAnswer.value = false;
      await nextTick();
      isPlayWholeQuestionAnimation.value = true;
      playCurrentQuestion(true);
    }
  }, 2000);
};

const questionParams = (question: IQuestion) => {
  var option_id = -1;
  question.option.forEach((option) => {
    if (option.select_this === 1) {
      option_id = option.option_id;
    }
  });
  return { listen_id: question.listen_id, option_id: option_id };
};

const reportQuestionAnswer = async () => {
  return new Promise(async function (resolve, reject) {
    if (isRelearn && currentQuestionIndex.value != questions.value!?.length - 1) {
      resolve(1);
      return;
    }

    const params = { section_id: sectionId! } as any;
    const listen = [];

    if (!isRelearn) {
      let question = currentQuestion();
      listen.push(questionParams(question));
    } else {
      questions.value?.forEach((question) => {
        listen.push(questionParams(question));
      });
    }
    params["listen"] = listen;

    try {
      await API.listenTrainReport(params);
      resolve(1);
    } catch {
      resolve(0);
    }
  });
};
</script>

<style scoped lang="scss">
.page-container {
  width: 100vw;
  height: 100vh;
  background-color: #ffffff;

  .container {
    position: absolute;
    width: 37.5rem;
    top: 6rem;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    overflow: auto;

    .tip {
      position: absolute;
      left: 2rem;
      top: 3.1rem;
      font-size: 1.6rem;
      font-family: xiaolai;
      color: $uni-text-color;
    }

    .ikon {
      position: absolute;
      top: 6.9rem;
      width: 33.5rem;
      height: 16rem;
      left: 50%;
      transform: translateX(-50%);
    }

    .loudspeaker {
      position: absolute;
      top: 25.5rem;
      width: 8rem;
      height: 8rem;
      left: 50%;
      transform: translateX(-50%);
    }



    .operate-container {
      position: absolute;
      bottom: 4.7rem;
      right: 0;
      left: 0;
      display: flex;
      flex-direction: column;

      .optionsContainer {
        height: 6rem;
        flex-direction: row;
        display: flex;
        justify-content: center;
        margin-bottom: 4rem;

        .optionContainer {
          position: relative;
          width: 6rem;
          height: 6rem;
          margin-right: 4rem;
          transform: scale(0.2);

          .option {
            position: absolute;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            border-width: 0.2rem;
            border-color: #a87f71;
            border-style: solid;
            text-align: center;
            align-items: center;
            display: flex;
            justify-content: center;
            color: $uni-text-color;
            font-size: 2.2rem;
            box-sizing: border-box;
          }

          .mask {
            position: absolute;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            // border-width: 0.2rem;
            background-color: #d1bbb2;
          }

          .maskDisappear {
            animation-name: maskDisappear;
            animation-duration: 0.15s;
            animation-timing-function: cubic-bezier(0.42, 0, 1, 1);
            animation-fill-mode: both;
          }
        }

        .optionContainer:last-child {
          margin-right: 0;
        }

        .optionAnimation {
          animation-name: optionAnimation;
          animation-duration: 0.15s;
          animation-timing-function: cubic-bezier(0.42, 0, 1, 1);
          animation-fill-mode: both;
        }
      }

      .button {
        display: flex;
        align-self: center;
        justify-content: center;
        width: 13rem;
        height: 5rem;
        line-height: 5rem;
        margin: 0;
        font-family: xiaolai;
        font-size: 1.7rem;
        border-radius: 1rem;
        color: $uni-text-color;
        border: 2px solid $uni-btn-border;
      }
    }

    .active {
      background-color: $uni-btn-prime;
    }

    .is-hover {
      color: rgba(255, 255, 255, 0.6);
    }
  }
}

@keyframes optionAnimation {
  from {
    transform: scale(0.2);
  }

  to {
    transform: scale(1);
  }
}

@keyframes maskDisappear {
  from {
    background-color: #d1bbb2;
  }

  to {
    background-color: transparent;
  }
}
</style>
